package com.example.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.SysSmsDao;
import com.example.enums.Events;
import com.example.enums.Status;
import com.example.po.SysSms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SysSmsServiceImpl extends ServiceImpl<SysSmsDao, SysSms> implements SysSmsService {

    Logger logger = LoggerFactory.getLogger(getClass());

    public static final String SMS = "SMS";

    @Value("${stateMachine.isMultiple}")
    private boolean isMultiple;

    @Resource
    private StateMachine<Status, Events> stateMachine;

    @Resource
    private SmsStateMachineBuilder smsStateMachineBuilder;

    @Override
    public SysSms applySms() {
        SysSms sysSms = new SysSms();
        sysSms.setStatus(Status.READY);
        saveOrUpdate(sysSms);
        return sysSms;
    }

    @Override
    public boolean sendSms(Long id) {
        SysSms sysSms = getById(id);
        sysSms.setStatus(Status.SUCCESS);
        return sendEvents(sysSms, Events.SUCCESSED) && saveOrUpdate(sysSms);
    }

    @Override
    public boolean failSms(Long id) {
        return false;
    }

    @Override
    public boolean commitSms(Long id) {
        SysSms sysSms = getById(id);
        sysSms.setStatus(Status.COMMIT);
        return sendEvents(sysSms, Events.COMMITED) && saveOrUpdate(sysSms);
    }

    @Override
    public boolean sendEvents(SysSms sysSms, Events events) {
        boolean flag = false;
        StateMachine<Status, Events> stateMachine = null;
        try {
            stateMachine = getStateMachine();
            stateMachine.start();
            Message message = MessageBuilder.withPayload(events).setHeader(SMS, sysSms).build();
            flag = stateMachine.sendEvent(message);
        } catch (Exception e) {
            logger.warn("状态机构建失败: {}", e.getMessage());
        }
        return flag;
    }

    @Override
    public StateMachine<Status, Events> getStateMachine() throws Exception {
        if (isMultiple) {
            return smsStateMachineBuilder.build();
        }
        return this.stateMachine;
    }
}
